package soulkun.library.utils.time

import android.annotation.SuppressLint
import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.*
import kotlin.math.absoluteValue

object DateUtils {

    private const val DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"
    private const val DATE_FORMAT = "yyyy-MM-dd"
    private const val EXACT_FORMAT = "yyyy-MM-dd HH:mm:ss SSS"
    private const val FILE_FORMAT = "yyyy-MM-dd(HH-mm-ss)"

    fun dateToStringWithFormat(date: Date, pattern: String): String? {
        val dateFormat = SimpleDateFormat(pattern, Locale.CHINA)
        return dateFormat.format(date)
    }

    fun dateToString(date: Date): String {
        return dateToStringWithFormat(date, DEFAULT_FORMAT)!!
    }

    fun dateToDateWithWeekDay(date: Date): String{
        val weekDays = arrayOf("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")
        val calendar = Calendar.getInstance().apply {
            time = date
        }
        return dateToStringWithFormat(date, DATE_FORMAT) + " " + weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1]
    }

    fun currentTime(): String {
        return dateToStringWithFormat(Date(), EXACT_FORMAT)!!
    }

    fun currentDate(): String{
        return dateToStringWithFormat(Date(), DATE_FORMAT)!!
    }

    fun currentDateWithWeekDay(): String{
        return dateToDateWithWeekDay(Date())
    }

    fun currentDateWithFormat(pattern: String): String? {
        return dateToStringWithFormat(Date(), pattern)
    }

    fun stringToDateWithFormat(string: String, pattern: String): Date?{
        val simpleDateFormat = SimpleDateFormat(pattern, Locale.CHINA)
        return simpleDateFormat.parse(string)
    }

    fun stringToDate(string: String): Date {
        return stringToDateWithFormat(string, DATE_FORMAT)!!
    }

    fun stringToDateWithWeekDay(string: String): String {
        return dateToDateWithWeekDay(stringToDate(string))
    }

    fun twoStringToDistanceDays(string1: String, string2: String): Long{
        val date1 = stringToDate(string1)
        val date2 = stringToDate(string2)
        val distance = (date1.time - date2.time).absoluteValue
        return distance / (1000 * 60 * 60 * 24)
    }

    fun stringToDistanceDays(string1: String): Long{
        val date1 = stringToDate(string1)
        val date2 = Date()
        val distance = (date1.time - date2.time).absoluteValue
        return distance / (1000 * 60 * 60 * 24)
    }

    /**
     * Timestamp转为yyyy-MM-dd格式
     */
    fun timestampToDate(timestamp: Timestamp): Date {
        val simpleDateFormat = SimpleDateFormat(DATE_FORMAT, Locale.CHINA)
        return simpleDateFormat.parse(simpleDateFormat.format(Date(timestamp.time)))
    }

}